<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/6
 * Time: 13:04
 */

namespace App\Model\Backstage;

use App\Model\Account\Type;
use App\Model\Base;
use App\Model\Backstage\RoomInfo;
use Illuminate\Support\Facades\DB;

class Customers extends Base
{
    public $customers;
    public $mobile_plan;
    public $customersfollow;
    public $customerfollowsource;
    protected $achievement_table;
    protected $room_table;
    protected $comm_cus = 2;  //公客对应ID   此数据后期对照正式ID值
    protected $private_cus = 1; //私客对应ID   此数据后期对照正式ID值
    public function __construct()
    {
        parent::__construct();
//        $this->customers = 'customers'.'_'.$this->branch_id;
        $this->customers = 'customers';
        $this->mobile_plan = 'mobile_plan';//移动端标记表
//        $this->achievement_table = 'achievement'.'_'.$this->branch_id;
        $this->customersfollow = 'customer_follow';//客源跟进表
        $this->customerfollowsource = 'customer_follow_source';//客源跟进提醒表
        $this->achievement_table = 'achievement';  //接口对接完成更换为上面表名
        $this->room_table = 'room_info';//接口对接完成更换为正式表名
    }

    public function listCustomers($pageLimit, $where = [], $keywords)
    {
        $list = DB::table($this->customers)
            ->leftjoin('user', 'c_employees_id', '=', 'u_id')
            ->where(function ($query) use($where, $keywords){
                $query->where($where)->where('c_user_name', 'like', '%'.$keywords.'%');
            })->orWhere(function ($query) use($where, $keywords) {
                $query->where($where)->where('c_user_phone', 'like', '%'.$keywords.'%');
            })->orWhere(function ($query) use($where, $keywords){
                $query->where($where)->where('c_area_address', 'like', '%'.$keywords.'%');
            })
            ->where('c_status', 1)
            ->select(['c_id', 'c_customers_type', 'c_user_name', 'c_user_phone', 'c_contact', 'c_contact_type', 'c_id_card', 'c_address',
            'c_trading_type', 'c_buy_status', 'c_private_guest', 'c_quality', 'c_area_id', 'c_secondary_area', 'c_area_address',
            'c_room', 'c_hall', 'c_toilet', 'c_balcony', 'c_acreage_max', 'c_acreage_min', 'c_price_max', 'c_price_min',
            DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'), 'c_entrust_type', 'c_source_type', 'c_user_level',
            'c_live_type', 'c_professional_type', 'c_user_intention', 'c_time_limit', 'c_use_type', 'c_floor', 'c_room_type', 'c_toward',
            'c_decorate_type', 'c_payment_type', 'c_complete', 'c_pay_type', 'c_remark', 'u_username',
                DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'),
                DB::raw('from_unixtime(c_created_at) as c_created_at'),
                DB::raw('from_unixtime(c_update_at) as c_update_at'), 'c_employees_id'
            ])
            ->orderBy('c_followup_time', 'desc')
            ->paginate($pageLimit);
        if(sizeof($list) == 0) {
            return false;
        }
        return $list;
    }
    //
    public function customersSameList($c_id)
    {
        return DB::table($this->customers)
            ->leftjoin('user', 'c_employees_id', '=', 'u_id')
            ->where('c_id', $c_id)
            ->where('c_status', 1)
            ->select(['c_id', 'c_customers_type', 'c_user_name', 'c_user_phone', 'c_contact', 'c_contact_type', 'c_id_card', 'c_address',
                'c_trading_type', 'c_buy_status', 'c_private_guest', 'c_quality', 'c_area_id', 'c_secondary_area', 'c_area_address',
                'c_room', 'c_hall', 'c_toilet', 'c_balcony', 'c_acreage_max', 'c_acreage_min', 'c_price_max', 'c_price_min',
                DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'), 'c_entrust_type', 'c_source_type', 'c_user_level',
                'c_live_type', 'c_professional_type', 'c_user_intention', 'c_time_limit', 'c_use_type', 'c_floor', 'c_room_type', 'c_toward',
                'c_decorate_type', 'c_payment_type', 'c_complete', 'c_pay_type', 'c_remark', 'u_username',
                DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'),
                DB::raw('from_unixtime(c_created_at) as c_created_at'),
                DB::raw('from_unixtime(c_update_at) as c_update_at'), 'c_employees_id'
            ])
            ->first();
    }

    //客源跟进
    public function customersFollow($c_id, $pageLimit)
    {
        $list = DB::table($this->customersfollow)
            ->leftJoin('user', 'cf_user_id', '=', 'u_id')
            ->where('cf_c_id',$c_id)
            ->select('cf_id','cf_c_id','cf_fllow_type', 'cf_content', 'u_username',
                DB::raw('from_unixtime(cf_created_at) as cf_created_at'))
            ->orderBy('cf_id', 'desc')
            ->paginate($pageLimit);
        if (sizeof($list) == 0) {
            return false;
        }
        return $list;

    }

    //根据客源的手机号  查询该客源是否已经录入过
    public function whether($c_user_phone, $c_id)
    {
        $cid = DB::table($this->customers)
            ->where('c_user_phone', $c_user_phone)
            ->where('c_id', '<>', $c_id)
            ->where('c_status', 1)
            ->value('c_id');
        if ($cid > 0){
            return $cid;
        }
        return false;
    }
    /**
     * 添加客源信息
     */
    public function addCustomers($params)
    {
        //开启事务
//        DB::beginTransaction();
        //添加客源信息
        return DB::table($this->customers)->insertGetId([
            'c_user_name'           => $params['c_user_name'],
            'c_user_phone'          => $params['c_user_phone'],
            'c_contact'             => isset($params['c_contact']) ? $params['c_contact'] : '',
            'c_contact_type'        => isset($params['c_contact_type']) ? $params['c_contact_type'] : '',
            'c_id_card'             => isset($params['c_id_card']) ? $params['c_id_card'] : '',
            'c_address'             => isset($params['c_address']) ? $params['c_address'] : '',
            'c_trading_type'        => $params['c_trading_type'],
            'c_buy_status'          => $params['c_buy_status'],
            'c_private_guest'       => $params['c_private_guest'],
            'c_quality'             => isset($params['c_quality']) ? $params['c_quality'] : '',
            'c_area_id'             => $params['c_area_id'],
            'c_secondary_area'      => $params['c_secondary_area'],
            'c_area_address'        => isset($params['c_area_address']) ? $params['c_area_address'] : '',
            'c_room'                => $params['c_room'],
            'c_hall'                => $params['c_hall'],
            'c_toilet'              => $params['c_toilet'],
            'c_balcony'             => $params['c_balcony'],
            'c_acreage_max'         => $params['c_acreage_max'],
            'c_acreage_min'         => $params['c_acreage_min'],
            'c_price_max'           => $params['c_price_max'],
            'c_price_min'           => $params['c_price_min'],
            'c_entrust_time'        => $params['c_entrust_time'],
            'c_entrust_type'        => $params['c_entrust_type'],
            'c_source_type'         => isset($params['c_source_type']) ? $params['c_source_type'] : '',
            'c_user_level'          => $params['c_user_level'],
            'c_live_type'           => isset($params['c_live_type']) ? $params['c_live_type'] : '',
            'c_professional_type'   => isset($params['c_professional_type']) ? $params['c_professional_type'] : '',
            'c_user_intention'      => isset($params['c_user_intention']) ? $params['c_user_intention'] : '',
            'c_time_limit'          => isset($params['c_time_limit']) ? $params['c_time_limit'] : '',
            'c_use_type'            => $params['c_use_type'],
            'c_floor'               => isset($params['c_floor']) ? $params['c_floor'] : '',
            'c_room_type'           =>isset($params['c_room_type']) ? $params['c_room_type'] : '',
            'c_toward'              => isset($params['c_toward']) ? $params['c_toward'] : '',
            'c_decorate_type'       => isset($params['c_decorate_type']) ? $params['c_decorate_type'] : '',
            'c_payment_type'        => isset($params['c_payment_type']) ? $params['c_payment_type'] : '',
            'c_complete'            => isset($params['c_complete']) ? $params['c_complete'] : '',
            'c_pay_type'            =>  isset($params['c_pay_type']) ? $params['c_pay_type'] : '',
            'c_remark'              => isset($params['c_remark']) ? $params['c_remark'] : '',
            'c_branch_id'           => $this->branch_id,
            'c_store_id'            => $this->store_id,
            'c_employees_id'        => $this->uid,
            'c_created_at'          => time(),
            'c_followup_time'       => time(),
            'c_created_at'          => time(),
            'c_update_at'           => time()
        ]);

    }

    /*
     * 客源智能匹配
     * Wu Ning
     */
    public function customersMatchingRoom($params){
        $where = [];
        $where[] = ['status', '=', 1];//过滤有效房源
        $where[] = ['room_status', '=', 1];//过滤非回收站房源
        //区域
        if(isset($params['c_area_id'])){
            $where[] = ['a_id',$params['c_area_id']];
        }
        //二级区域
        if(isset($params['c_secondary_area'])){
            $where[] = ['building_id',$params['c_secondary_area']];
        }
        //具体地址不做过滤
        //交易类型  求租=》出租&租售  求购=》出售  租购=》All
        if(isset($params['c_trading_type']) && $params['c_trading_type'] != ''){
            $where[] = ['trading_type', $params['c_trading_type']];
        }
        //用途
        if(isset($params['c_use_type']) && $params['c_use_type'] != ''){
            $where[] = ['use_type' , $params['c_use_type']];
        }
        //房型
        if(isset($params['room']) && isset($params['hall']) && isset($params['toilet']) && isset($params['balcony'])){
            //房源数据库存储json字符串 r_info
//            $where[] = ['room' , $params['r_info']];
//
        }
        //面积 c_acreage_max  c_acreage_min
        if(isset($params['c_acreage_min']) && $params['c_acreage_min'] != ''){   //开始面积
            $where[] = ['r_acreage', '>=', $params['c_acreage_min']];
        }
        if(isset($params['c_acreage_max']) && $params['c_acreage_max'] != ''){   //结束面积
            $where[] = ['r_acreage', '<=', $params['c_acreage_max']];
        }
        //价格 给价格类型值
        //租价
       if(isset($params['c_rent_price_min']) && $params['c_rent_price_min'] != ''){
                $where[] = ['rents', '>=', $params['c_rent_price_min']];
            }
        if(isset($params['c_rent_price_max']) && $params['c_rent_price_max'] != ''){
                $where[] = ['rents', '<=', $params['c_rent_price_max']];
            }
      //售价
        if(isset($params['c_price_min']) && $params['c_price_min'] != ''){
                $where[] = ['price', '>=', $params['c_price_min']];
            }
        if(isset($params['c_price_max']) && $params['c_price_max'] != ''){
                $where[] = ['price', '<=', $params['c_price_max']];
            }

        $roomInfo = new RoomInfo();
        $list = $roomInfo->listRoom(env('PAGE_LIMIT_ADMIN'), $where, '');
        if(sizeof($list) > 0){
        return $list;
        }
        return false;
    }

    /***根据客源ID 修改客源信息
     * @param $params
     * @return mixed
     */
    public function updateCustomers($params)
    {
        return DB::table($this->customers)
            ->where('c_id', $params['c_id'])
            ->update([
                'c_user_name'           => $params['c_user_name'],
                'c_user_phone'          => $params['c_user_phone'],
                'c_contact'             => isset($params['c_contact']) ? $params['c_contact'] : '',
                'c_contact_type'        => isset($params['c_contact_type']) ? $params['c_contact_type'] : '',
                'c_address'             => isset($params['c_address']) ? $params['c_address'] : '',
                'c_trading_type'        => $params['c_trading_type'],
                'c_buy_status'          => $params['c_buy_status'],
                'c_private_guest'       => $params['c_private_guest'],
                'c_quality'             => isset($params['c_quality']) ? $params['c_quality'] : '',
                'c_area_id'             => $params['c_area_id'],
                'c_secondary_area'      => $params['c_secondary_area'],
                'c_area_address'        =>isset($params['c_area_address']) ? $params['c_area_address'] : '',
                'c_room'                => $params['c_room'],
                'c_hall'                => $params['c_hall'],
                'c_toilet'              => $params['c_toilet'],
                'c_balcony'             => $params['c_balcony'],
                'c_acreage_max'         => $params['c_acreage_max'],
                'c_acreage_min'         => $params['c_acreage_min'],
                'c_price_max'           => $params['c_price_max'],
                'c_price_min'           => $params['c_price_min'],
                'c_entrust_time'        => $params['c_entrust_time'],
                'c_entrust_type'        => $params['c_entrust_type'],
                'c_source_type'         => isset($params['c_source_type']) ? $params['c_source_type'] : '',
                'c_user_level'          => $params['c_user_level'],
                'c_live_type'           => isset($params['c_live_type']) ? $params['c_live_type'] : '',
                'c_professional_type'   => isset($params['c_professional_type']) ? $params['c_professional_type'] : '',
                'c_user_intention'      => isset($params['c_user_intention']) ? $params['c_user_intention'] : '',
                'c_time_limit'          => isset($params['c_time_limit']) ? $params['c_time_limit'] : '',
                'c_use_type'            => $params['c_use_type'],
                'c_floor'               => $params['c_floor'],
                'c_room_type'           => isset($params['c_room_type']) ? $params['c_room_type'] : '',
                'c_toward'              => isset($params['c_toward']) ? $params['c_toward'] : '',
                'c_decorate_type'       => isset($params['c_decorate_type']) ? $params['c_decorate_type'] : '',
                'c_payment_type'        => isset($params['c_payment_type']) ? $params['c_payment_type'] : '',
                'c_complete'            => isset($params['c_complete']) ? $params['c_complete'] : '',
                'c_pay_type'            => isset($params['c_pay_type']) ? $params['c_pay_type'] : '',
                'c_private_guest'       => $params['c_private_guest'],
                'c_followup_time'       => time(),
                'c_update_at'           => time()
            ]);
    }

    /**
     * 根据客源ID 删除客源信息 同时删除该客源的所有跟进  客源的提醒
     * @param $cId 客源ID
     * @return mixed
     */
    public function delCustomers($cId)
    {
        $cIds = DB::table($this->customers)->where('c_id', $cId)->update(['c_status' => 3]);
        $cfId = DB::table($this->customersfollow)->where('cf_c_id', $cId)->delete();
        $cfsId = DB::table($this->customerfollowsource)->where('cfs_type_id', $cId)->where('cfs_type', 2)->delete();
        if ($cIds) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据客源ID 把客源信息放到回收站
     * @param $cId 客源ID
     * @return mixed
     */
    public function recyclebinCustomers($cId)
    {
        return DB::table($this->customers)->where('c_id', $cId)->update(['c_status' => 2]);
    }


    /**中介公司下 回收站客源的信息列表
     * @param $pageLimit
     * @return mixed
     */
    public  function recycleBinList($pageLimit)
    {
        return DB::table($this->customers)
            ->leftjoin('user', 'c_employees_id', '=', 'u_id')
            ->where('c_branch_id', $this->branch_id)
            ->where('c_status',2)
            ->select(['c_buy_status', 'c_user_name', 'c_area_address', 'c_entrust_time', 'u_username',  DB::raw('from_unixtime(c_followup_time) as c_followup_time'),])
            ->orderBy('c_followup_time', 'desc')
            ->paginate($pageLimit);
    }



    /**
     * 修改客源状态信息，增加员工业绩计算
     * 购买状态(1有效 2预定 3已购 4已租 5我购 6我租 7暂缓 8未知 9无效)
     */
    public function saveCustomersStatus($param){
        if($param['status'] == 5 || $param['status'] == 6){  //判断是否为 5我购 6我租

//            $res = DB::table($this->achievement_table)->where(['room_id' => $param['room_id'],'customer_id' => $param['customer_id']])->first();
//
//            if($res){
//                return ['code' => 0,'msg' => '该客户已经完成'];
//            }

            //开启事务
            DB::beginTransaction();
            try
            {
                DB::table($this->room_table)->where('id', $param['room_id'])->update(['status' => $param['status']]);
                DB::table($this->customers)->where('c_id' , $param['customer_id'])->update(['c_buy_status' => $param['status']]);


                if($param['type'] == 1){  //独立完成订单
                    $data['a_uid'] = $this->uid;
                    $data['a_room_id'] = $param['room_id'];
                    $data['a_customer_id'] = $param['customer_id'];
                    $data['a_ubid'] = $this->store_id;
                    $data['a_money'] = $param['money'];
                    $data['a_created_at'] = time();
                    $data['a_rem
                    ark'] = $param['remark'];
                }else{  //多人配合
                    $data = [];
                    $rate_arr = explode(',' , $param['rate']);
                    $user_id = explode(',' , $param['u_id']);
                    $rate = array_sum($rate_arr);
                    if($rate > 10){
                        return ['code' => 0, 'msg' => '分成设置错误'];
                    }
                    foreach($user_id as $k => $v){
                        $data[$k]['a_uid'] = $v;
                        $data[$k]['a_room_id'] = $param['room_id'];
                        $data[$k]['a_customer_id'] = $param['customer_id'];
                        $data[$k]['a_ubid'] = $this->store_id;
                        $data[$k]['a_money'] = sprintf("%.2f",substr(sprintf("%.3f", $rate_arr[$k] / $rate * $param['money'] ), 0, -2));
                        $data[$k]['a_created_at'] = time();
                        $data[$k]['a_remark'] = $param['remark'];
                    }
                }

                DB::table($this->achievement_table)->insert($data);
                DB::commit();
                return ['code' => 1, 'msg' => '添加成功'];
            }
            catch(Exception $e)
            {
                DB::rollback();
                return ['code' => 2, 'msg' => '添加失败'];
            }
        }else{    //否则不处理业绩问题，直接修改房源状态
            $res = DB::table($this->customers)->where('c_id',$param['customer_id'])->update(['c_buy_status'=>$param['status']]);
            if($res){
                return ['code' => 1, 'msg' => '修改成功'];
            }else{
                return ['code' => 2, 'msg' => '修改失败'];
            }
        }
    }


    /**
     * @param array $map
     * @param $pageLimit
     * @return mixed
     * 员工录入客源排行
     */
    public function customersAchievementList($map = [],$pageLimit){

        $where = [
            'u_b_id' => $this->branch_id,
            'is_del' => 0,
            'u_status' => 1
        ];
        $user_list = DB::table('user')
            ->where($where)
            ->select(['u_id','u_username','u_type'])
            ->get()
            ->toArray();
        foreach($user_list as $k => $v){
            $num = DB::table($this->customers)->where($map)->where('c_employees_id', $v->u_id)->count();
            $v->num = $num;
        }
        $list = json_encode($user_list);
        $list = json_decode($list,true);
        array_multisort(array_column($list,'num'),SORT_DESC,$list);
        return $list;
    }

    /**
     * 添加房源时根据条件智能匹配出对应客源信息
     */
    public function getCustomersList($map, $limit){
        $list = DB::table($this->customers)->where($map)->take($limit)->orderBy('c_created_at','desc')->get();
        if($list){
            foreach ($list as $key=>$val) {
                $val->c_trading_type_name      = Type::getTypeDetail($val->c_trading_type);//交易类型
                $val->c_buy_status_name        = Type::getTypeDetail($val->c_buy_status);//购买状态
                $val->c_room_name              = Type::getTypeDetail($val->c_room);//房型
                $val->c_hall_name              = Type::getTypeDetail($val->c_hall);//厅
                $val->c_toilet_name            = Type::getTypeDetail($val->c_toilet);//卫
                $val->c_balcony_name           = Type::getTypeDetail($val->c_balcony);//阳台
                $val->c_source_type_name       = Type::getTypeDetail($val->c_source_type);//来源
                $val->c_entrust_type_name      = Type::getTypeDetail($val->c_entrust_type);//委托方式
                $val->c_user_level_name        = Type::getTypeDetail($val->c_user_level);//等级
                $val->c_live_type_name         = Type::getTypeDetail($val->c_live_type);//现住
                $val->c_professional_type_name = Type::getTypeDetail($val->c_professional_type);//类别
                $val->c_user_intention_name    = Type::getTypeDetail($val->c_user_intention);//意向
                $val->c_time_limit_name        = Type::getTypeDetail($val->c_time_limit);//期限
                $val->c_use_type_name         = Type::getTypeDetail($val->c_use_type);//用途
                $val->c_room_type_name         = Type::getTypeDetail($val->c_room_type);//房屋类型
                $val->c_toward_name            = Type::getTypeDetail($val->c_toward);//朝向
                $val->c_decorate_type_name     = Type::getTypeDetail($val->c_decorate_type);//装修
                $val->c_payment_type_name      = Type::getTypeDetail($val->c_payment_type);//付款
                //配套名字 c_complete
                $c_complete_name = array();//配套名字
                $completeArr = explode(',', $val->c_complete);
                foreach ($completeArr as $ke=>$va) {
                    array_push($c_complete_name, Type::getTypeDetail($va));
                }
                $val->c_complete_name = implode(',', $c_complete_name);//配套的名字
                $val->c_pay_type_name      = Type::getTypeDetail($val->c_pay_type);//付佣
            }
        }
        return $list;
    }


    /**
     * @param $param
     * 自动更新客源对应信息
     */
    public function updateRuleCustomers($param){
        $map = $this->dateMap($param);
        return $this->saveCustomersAuth($map, $param);
    }

    /**
     * @param $param
     * @return array
     * 日期类型判断条件
     */
    public function dateMap($param){
        $map = [];
        $times = time() - 60 * 60 * 24 * $param['a_day_num'];
        switch($param['a_date_type']){   //判断查找时间类型
            case 0: //最后跟进日期
                $map[] = ['c_followup_time', '<=', $times];
                break;
            case 1: //委托日
                $map[] = ['c_entrust_time', '<=', $times];
                break;
            case 2:  //录入日
                $map[] = ['c_created_at', '<=', $times];
                break;
            default:
                break;
        }
        return $map;
    }
    /**
     * @param $map
     * @param $params
     * @return mixed
     * 修改客源私-公
     */
    public function saveCustomersAuth($map, $params){

        $map[] = ['c_customers_type', $this->private_cus];
        $map[] = ['c_store_id', $params['a_d_id']]; //部门ID
        //以下所有判断如果类型值为false则代表全部，不作为过滤条件
        if($params['a_trade_type']){  //交易类型
            $map[] = ['c_trading_type', $params['a_trade_type']];
        }
        if($params['a_m_status']){   //客源状态
            $map[] = ['c_buy_status', $params['a_m_status']];
        }
        if($params['a_use_type']){  //客源用途
            $map[] = ['c_use_type', $params['a_use_type']];
        }
        if($params['a_entrust_way']){  //委托方式
            $entrust_arr = explode(',', $params['a_entrust_way']);
            return DB::table($this->customers)
                ->where($map)
                ->whereIn('c_entrust_type', $entrust_arr)
                ->update([
                'c_customers_type' => $this->comm_cus,
                'c_update_at'      => time()
            ]);
        }else{
            return DB::table($this->customers)->where($map)->update([
                'c_customers_type' => $this->comm_cus,
                'c_update_at'      => time()
            ]);
        }

    }

    /**
     * @param $param
     * @param $type
     * @return mixed
     * 移动客源
     */
    public function moves($param, $type){
        $map = $this->moveMap($param);
        if($type == 1 ){
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                $ids = DB::table($this->customers)
                        ->where($map)
                        ->limit($param['num'])
                        ->orderBy('c_id', 'desc')
                        ->pluck('c_id');
                return DB::table($this->customers)
                    ->whereIn('c_id', $ids)
                    ->update([
                        'c_store_id' => $param['to_d_id'],
                        'c_employees_id' => $param['to_uid'],
                        'c_update_at' => time()
                    ]);
            }else{
                return DB::table($this->customers)
                    ->where($map)
                    ->update([
                        'c_store_id' => $param['to_d_id'],
                        'c_employees_id' => $param['to_uid'],
                        'c_update_at' => time()
                    ]);
            }

        }else{
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                return DB::table($this->customers)
                    ->where($map)
                    ->limit($param['num'])
                    ->orderBy('c_id', 'desc')
                    ->pluck('c_id');
            }else{
                return DB::table($this->customers)
                    ->where($map)
                    ->orderBy('c_id', 'desc')
                    ->pluck('c_id');
            }
        }
    }

    /**
     * @param $param
     * @return array
     * 判断条件
     */
    public function moveMap($param){
        $map[] = ['c_store_id', $param['out_d_id']];  //部门ID
        $map[] = ['c_employees_id', $param['out_uid']];  //用户ID
        $map[] = ['c_status', 1];

        if(isset($param['c_trading_type']) && $param['c_trading_type'] != ''){ //交易类型 求购 求租 租购
            $map[] = ['c_trading_type', $param['c_trading_type']];
        }
        if(isset($param['c_buy_status']) && $param['c_buy_status'] != ''){  //客源状态
            $map[] = ['c_buy_status', $param['c_buy_status']];
        }
        //按跟进时间
        if(isset($param['start_time']) && $param['start_time'] != ''){ //开始时间
            $map[] = ['c_followup_time', '>=', strtotime($param['start_time'])];
        }
        if(isset($param['end_time']) && $param['end_time'] != ''){  //结束时间
            $map[] = ['c_followup_time', '<=', strtotime($param['end_time'])];
        }
        return $map;
    }

    /**
     * @param $params
     * @return mixed
     * 公到私  私到公
     */
    public function turns($params){
        $map = $this->dateMap($params); //时间数组
        //部门
        if(isset($params['a_d_id']) && $params['a_d_id'] != ''){
            $map[] = ['c_store_id', $params['a_d_id']];
        }
        //员工
        if(isset($params['a_uid']) && $params['a_uid'] != ''){
            $map[] = ['c_employees_id', $params['a_uid']];
        }
        //区域
        if(isset($params['a_code']) && $params['a_code'] != ''){
            $area_code = $params['a_code'];
            $map[] =['c_area_id', DB::raw("FIND_IN_SET($area_code,c_area_id)")] ;
        }
        //交易类型
        if(isset($params['trading_type']) && $params['trading_type'] != ''){
            $map[] = ['c_trading_type', $params['trading_type']];
        }
        //状态
        if(isset($params['status']) && $params['status'] != ''){
            $map[] = ['c_buy_status', $params['status']];
        }
        $updateData = [];
        if($params['turn_type'] == 2){   //私转公
            $map[] = ['c_customers_type', $this->private_cus];
            $updateData = [
                'c_customers_type' => $this->comm_cus,
                'c_update_at' => time()
            ];
        } elseif($params['turn_type'] == 3){  //公转私
            $map[] = ['c_customers_type', $this->comm_cus];
            $updateData = [
                'c_customers_type' => $this->private_cus,
                'c_update_at' => time()
            ];
        }
        return DB::table($this->customers)
            ->where($map)
            ->update($updateData);
    }

    /**
     * 添加标记
     */
    public function addplan($params){

        return DB::table($this->mobile_plan)->insertGetId([
            'hmp_room_customer'   => $params['hmp_room_customer'],
            'hmp_room_customer_id'   => $params['hmp_room_customer_id'],
            'hmp_sign_type'   => $params['hmp_sign_type'],
            'hmp_status'   => $params['hmp_status'],
            'hmp_plan_time'   => $params['hmp_plan_time'],
            'hmp_user_id'   => $params['hmp_user_id'],//员工Id
            'hmp_user_department'   => $params['hmp_user_department'],//部门Id
            'hmp_created_time'   => $params['hmp_created_time'],
            'hmp_update_time'   => $params['hmp_update_time']
        ]);
    }

    //移动端获取个人信息
    function getPersonalInfo(){
        return  DB::table('staff')
                   ->where('area_manager_id', $this->uid)
                    ->select(['branch_id', 'sex','birthday','jiguan','nation','college','political_face','speciality','record_type','people_num','phone','email','address','bank_num',
                    'bank_remark','personal_profile','post','entry_time','s_update_time','source'])
                    ->get();

    }
}